import axios from 'axios'
import { message } from 'ant-design-vue'
import JSONBIG from 'json-bigint'
import * as allStore from '@/stores/modules/user.js'

export const serverHost = '/prod-api'
// export const serverHost = 'http://192.168.3.48:8088'

axios.defaults.baseURL = serverHost

// 解决长整数丢失精度问题
axios.defaults.transformResponse = [
  function (data) {
    const json = JSONBIG({
      storeAsString: true
    })
    return json.parse(data)
  }
]

const http = axios.create()
// 请求拦截
http.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    config.headers['Authorization'] = 'Bearer ' + token
    // if (!token) {
    //   window.open('_self')
    // }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截
http.interceptors.response.use(
  (res) => {
    if (res.data.code === 401) {
      message.error({
        content: '未登录或已过期，请重新登录',
        duration: 1,
        onClose: () => {
          let userStore = allStore.useUserStore()
          userStore.logout()
        }
      })
      return Promise.reject(res.data)
    }
    if (res.data.code !== 200) {
      message.error(res.data.msg)
      return Promise.reject(res.data)
    }
    return { ...res.data, resultObject: res.data.data }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export const request = ({ url, method = 'POST', headers = {}, timeout = 30000, data = {} }) => {
  const methodOfParams = ['GET', 'DELETE']

  return new Promise((resolve, reject) => {
    method = method.toLocaleUpperCase()
    http({
      url,
      method,
      headers: { 'Content-Type': 'application/json', ...headers },
      timeout,
      params: methodOfParams.includes(method) ? data : null,
      data: !methodOfParams.includes(method) ? data : null
    })
      .then(resolve)
      .catch(reject)
  })
}
